import React from 'react'
import {
  Checkbox,
  Spin,
  //  Form, Space
} from 'antd'
import { LdhFieldSet } from '@biz/PageCompnents'
import {
  LdhButton,
  LdhFormItem,
  LdhInput,
  LdhObjListSelect,
  LdhFormItemTip,
  LdhSelect,
} from '@biz/Components'
import BaseDetailPage from '@biz/BaseDetailPage'
import { PublicAction } from '@/base/BaseAction'
import { createAction } from '../Action'
import Config from '../config'
import Store from '../Store'
import {
  onPostShopAccountListByPlatformTypeXhr,
  onGetPlatformTypeXhr,
} from '@/api/coupon'
// import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons'

import '../style.less'
import MapModal from './MapModal'

const prefix = 'shop-detail'
export default class ShopDetail extends BaseDetailPage {
  constructor(props) {
    super(props)
    this.action = createAction()
    this.config = Config(this.action)
    this.store = new Store(props, this.config, this.action)
    this.className = prefix
  }
  componentDidMount() {
    super.componentDidMount()

    PublicAction.allShopAccountList(({ voList = [] }) =>
      this.setState({ shopAccountList: voList })
    )
    PublicAction.allWashProductList(({ voList = [] }) =>
      this.setState({ washProductList: voList })
    )

    // 获取停车场类型列表
    this.getPlatformTypeList()
  }

  // 获取停车场类型列表
  getPlatformTypeList = async () => {
    try {
      const res = await onGetPlatformTypeXhr({})
      if (res?.success) {
        const platformTypeList =
          res?.voList?.map((item) => {
            return {
              label: item?.parkName,
              value: item?.platformType,
            }
          }) || []
        this.setState({ platformTypeList })
      } else {
        this.setState({ platformTypeList: [] })
      }
    } catch (error) {
      console.error('获取停车场类型列表失败:', error)
      this.setState({ platformTypeList: [] })
    }
  }

  onGetDetailCompleted(detail) {
    let { province, city, district } = detail
    detail.pcdAddress = [province, city, district].join(' ')

    // 处理 parkSystemAccountId 为 0 的情况
    if (detail.parkSystemAccountId === 0) {
      detail.parkSystemAccountId = undefined
    }
    if (!!detail?.platformType) {
      this.handlePlatformTypeChange(detail.platformType)
    }

    // 处理 otherManagerList：将对象数组转换为 ID 数组用于表单显示
    if (detail.otherManagerList && Array.isArray(detail.otherManagerList)) {
      detail.otherManagerIds = detail.otherManagerList.map(
        (item) => item.managerId
      )
    }
  }
  onSubmit(values) {
    let { detailStatus, detail, shopAccountList = [] } = this.state
    let vo = { ...detail, ...values }

    // 处理 otherManagerIds：将 ID 数组转换为对象数组
    if (
      values.otherManagerIds &&
      Array.isArray(values.otherManagerIds) &&
      values.otherManagerIds.length > 0
    ) {
      vo.otherManagerList = values.otherManagerIds.map((managerId) => {
        const account = shopAccountList.find(
          (item) => item.id === managerId || item.id === String(managerId)
        )
        return {
          managerId: managerId,
          name: account?.name || account?.username || '',
          phone: account?.phone || '',
        }
      })
    } else {
      vo.otherManagerList = []
    }
    // 删除临时字段
    delete vo.otherManagerIds

    this.action[detailStatus](vo)
  }
  handlePosChange(pos) {
    let { detail } = this.state
    let { province, city, district } = pos
    pos.pcdAddress = [province, city, district].join(' ')
    detail = { ...detail, ...pos }
    this.form().setFieldsValue(pos)
    this.setState({ detail })
  }

  // 添加平台类型变化处理函数
  handlePlatformTypeChange = async (value) => {
    try {
      const res = await onPostShopAccountListByPlatformTypeXhr({
        platformType: value,
      })
      if (res?.success) {
        const formattedList = res.voList || []
        this.setState({
          parkAccountList: formattedList,
          detail: {
            ...this.state.detail,
            // 只有在切换时才清空 parkSystemAccountId
            parkSystemAccountId:
              this.state.detail.platformType !== value
                ? undefined
                : this.state.detail.parkSystemAccountId,
          },
        })
        this.form().setFieldsValue({
          parkSystemAccountId:
            this.state.detail.platformType !== value
              ? undefined
              : this.state.detail.parkSystemAccountId,
        })
      } else {
        // 如果没有成功获取列表，清空 parkAccountList
        this.setState({ parkAccountList: [] })
      }
    } catch (error) {
      console.error('获取商户账号列表失败:', error)
      // 在发生错误时清空 parkAccountList
      this.setState({ parkAccountList: [] })
    }
  }

  renderDetail(isDetail) {
    let {
      loading,
      detail,
      shopAccountList = [],
      washProductList = [],
      parkAccountList = [],
      platformTypeList = [],
    } = this.state

    let { lat, lng } = detail
    return (
      <Spin spinning={loading}>
        <LdhFieldSet title="基本信息" btn={!isDetail}>
          <LdhFormItem label="名称" name="name" required isDetail={isDetail}>
            <LdhInput maxLength={60} showCount placeholder="请输入展示名称" />
          </LdhFormItem>

          <LdhFormItem
            label="省市区"
            name="pcdAddress"
            required
            isDetail={isDetail}
          >
            <LdhInput
              maxLength={60}
              showCount
              placeholder="请选择定位"
              disabled
            />
          </LdhFormItem>
          <LdhFormItem label="街道" name="street" required isDetail={isDetail}>
            <LdhInput maxLength={60} showCount placeholder="请填写" />
          </LdhFormItem>
          {isDetail ? (
            <LdhFormItem label="定位" name="pos">
              <div>
                经度： <b className="mr-20">{lng}</b> 纬度：<b>{lat}</b>
              </div>
            </LdhFormItem>
          ) : (
            <div>
              <LdhFormItemTip>若定位时街道信息不准确，手工调整</LdhFormItemTip>
              <LdhFormItem label="定位" name="pos" isDetail={isDetail}>
                <div>
                  <LdhButton onClick={this.action.doMapPos}>点击设置</LdhButton>
                </div>
              </LdhFormItem>
              <div className="pos-value">
                经度： <b className="mr-20">{lng}</b> 纬度：<b>{lat}</b>
              </div>
            </div>
          )}

          {/*  <LdhFormItem label="省份" name="province" required isDetail={isDetail}>
                    <LdhInput maxLength={8} showCount placeholder="" className="w-120"/>
                </LdhFormItem>
                <LdhFormItem label="城市" name="city" required isDetail={isDetail}>
                    <LdhInput maxLength={8} showCount placeholder=""  className="w-120"/>
                </LdhFormItem>
                <LdhFormItem label="区县" name="district" required isDetail={isDetail}>
                    <LdhInput maxLength={8} showCount placeholder="30.299904"  className="w-120"/>
                </LdhFormItem>
                <LdhFormItem label="街道" name="street" required isDetail={isDetail}>
                    <LdhInput maxLength={128} showCount placeholder="请输入街道，门牌号"/>
                </LdhFormItem>
                <Row>
                    <Col span={16}>
                        <LdhFormItem label="省份" name="province" required isDetail={isDetail}>
                            <LdhInput maxLength={8} showCount placeholder="" className="w-120"/>
                        </LdhFormItem>
                    </Col>
                    <Col span={8}>
                        <LdhFormItem label="省份" name="province" required isDetail={isDetail}>
                            <LdhInput maxLength={8} showCount placeholder="" className="w-120"/>
                        </LdhFormItem>
                    </Col>
                </Row>*/}

          <LdhFormItem
            label="联系电话"
            name="contact"
            required
            isDetail={isDetail}
            rules={[
              { pattern: window.CONFIG.REG_PHONE, message: '不符合手机号规则' },
            ]}
          >
            <LdhInput maxLength={11} showCount placeholder="请输入联系电话" />
          </LdhFormItem>
          {/* <LdhFormItem label="门店到期时间" name="expiredDate" required isDetail={isDetail}>
                    <LdhInput maxLength={60} showCount/>
                </LdhFormItem>*/}
          <LdhFormItem
            label="美团门店ID"
            name="meituanShopId"
            isDetail={isDetail}
          >
            <LdhInput placeholder="请输入" />
          </LdhFormItem>
          <LdhFormItem
            label="点评门店ID"
            name="dianpingShopId"
            isDetail={isDetail}
          >
            <LdhInput placeholder="请输入" />
          </LdhFormItem>
          <LdhFormItem
            label="抖音门店ID"
            name="douyinShopId"
            isDetail={isDetail}
          >
            <LdhInput placeholder="请输入" />
          </LdhFormItem>
        </LdhFieldSet>

        <LdhFieldSet title="门店账号信息">
          <LdhFormItem label="商家管理员账号" name="managerId" required>
            <LdhObjListSelect
              list={shopAccountList}
              placeholder="请选择商家账号"
              isDetail={isDetail}
            />
          </LdhFormItem>

          <LdhFormItem label="其他商家账号" name="otherManagerIds">
            <LdhObjListSelect
              list={shopAccountList}
              placeholder="请选择商家账号"
              mode="multiple"
              maxTagCount={3}
              maxTagPlaceholder={(omittedValues) => `+${omittedValues.length}`}
              isDetail={isDetail}
            />
          </LdhFormItem>
        </LdhFieldSet>

        <LdhFieldSet title="门店停车信息">
          <LdhFormItem
            label="停车政策"
            name="parkingPolicy"
            isDetail={isDetail}
          >
            <LdhInput maxLength={255} showCount placeholder="请输入停车政策" />
          </LdhFormItem>
          <LdhFormItem
            label="支持停车优惠"
            name="supportParkingDiscount"
            isDetail={isDetail}
            isCheckbox
            checkboxValueType="SUPPORT"
          >
            <Checkbox></Checkbox>
          </LdhFormItem>
          <div className="pos-value tip">
            注：如果支持停车优惠，需要后台配置优惠券获取的方式及相关账号
          </div>
          <LdhFormItem
            label="请选择停车场类型"
            name="platformType"
            isDetail={isDetail}
            isSelect
            options={platformTypeList}
          >
            <LdhSelect
              options={platformTypeList}
              onChange={this.handlePlatformTypeChange}
            />
          </LdhFormItem>
          <div className="pos-value tip">
            注：捷停车: 提交车牌给三方系统;保信: 发放二维码,从服务号二次跳转
          </div>
          <LdhFormItem
            label="请选择商户帐号"
            name="parkSystemAccountId"
            isDetail={isDetail}
            isSelect
            options={parkAccountList}
          >
            <LdhObjListSelect
              list={parkAccountList}
              placeholder="请选择商户账号"
              isDetail={isDetail}
            />
          </LdhFormItem>
          <LdhFormItem
            label="订单时长要求"
            name="parkingOrderDuration"
            isDetail={isDetail}
            rules={[
              { pattern: window.CONFIG.REG_NUM_INT, message: '请输入整数' },
            ]}
          >
            <LdhInput placeholder="" />
          </LdhFormItem>
          <div className="pos-value tip">
            注：如果支持停车优惠，则输入洗车订单时长的要求，单位：分钟。当洗车订单时长大于等于此值时，才能领取优惠券。
          </div>

          <LdhFormItem
            label="免费停车时长"
            name="parkingFreeHour"
            isDetail={isDetail}
            rules={[
              { pattern: window.CONFIG.REG_NUM_D2, message: '请输入数字' },
            ]}
          >
            <LdhInput placeholder="" />
          </LdhFormItem>
          <div className="pos-value tip">
            注：如果支持停车优惠，则输入免费停车时长，单位：小时。提示用户领取停车券可以抵扣多少时间的免费停车。
          </div>

          <LdhFormItem
            label="停车券领取时间要求"
            name="parkingDiscountApplyDelta"
            isDetail={isDetail}
            rules={[
              { pattern: window.CONFIG.REG_NUM_INT, message: '请输入整数' },
            ]}
          >
            <LdhInput placeholder="" />
          </LdhFormItem>
          <div className="pos-value tip">
            注：如果支持停车优惠，则输入停车券领取时间的要求，单位：分钟。当订单完结后需要在几分钟内领取停车券，超过此时间间隔则不能再领取停车券。
          </div>

          <LdhFormItem
            label="会员订单时长要求"
            name="parkingVipOrderDuration"
            isDetail={isDetail}
            rules={[
              { pattern: window.CONFIG.REG_NUM_INT, message: '请输入整数' },
            ]}
          >
            <LdhInput placeholder="" />
          </LdhFormItem>
        </LdhFieldSet>

        <LdhFieldSet title="门店结算规则">
          <LdhFormItem label="自助洗车计费" name="washProductId" required>
            <LdhObjListSelect
              list={washProductList}
              placeholder="请选择"
              isDetail={isDetail}
            />
          </LdhFormItem>

          <LdhFormItem
            label="结算折扣"
            name="discount"
            required
            isDetail={isDetail}
            rules={[
              { pattern: window.CONFIG.REG_NUM_D2, message: '折扣保留2位小数' },
              {
                validator: (rule, newValue, callback) => {
                  if (
                    newValue != '' &&
                    newValue != undefined &&
                    Number(newValue) < 0
                  ) {
                    return Promise.reject('折扣只允许0~1之间')
                  }
                  if (
                    newValue != '' &&
                    newValue != undefined &&
                    Number(newValue) > 1
                  ) {
                    return Promise.reject('折扣只允许0~1之间')
                  }
                  return Promise.resolve()
                },
              },
            ]}
          >
            <LdhInput placeholder="根据订单金额给商家结算的比例" />
          </LdhFormItem>
          <div className="pos-value tip">
            注：用户订单为10元，若结算折扣为0.9，则商家获得9元，平台获得1元
          </div>
        </LdhFieldSet>

        <MapModal
          store={this.state}
          action={this.action}
          onSubmit={this.handlePosChange.bind(this)}
        ></MapModal>
      </Spin>
    )
  }
}
